package com.alipay.service.listener;

import com.alipay.mapper.TransferTaskMapper;
import com.alipay.model.dto.TransDto;
import com.alipay.model.entity.TransTaskEntity;
import com.alipay.model.enums.TaskStatusEnum;
import com.alipay.util.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * @author Jun
 * 监听B增加余额成功，修改A转账状态为完成
 */
@Slf4j
@Service
public class TansTaskIncreaseMessageSuccessListener {

    @Resource
    private TransferTaskMapper transferTaskMapper;

    @Transactional(rollbackFor = Exception.class)
    @RabbitListener(queues = "${rabbitmq.success.queue}")
    protected void onMessage(String message) {

        TransDto transDto = JsonUtil.fromJson(message, TransDto.class);
        try {
            // 参数有效性校验
            if (transDto == null) {
                return;
            }

            // 查询A库的任务状态
            TransTaskEntity transferTaskDB = transferTaskMapper.getTransferTaskByTransId(transDto.getTransId());

            // 更新为收款完成，乐观锁控制
            transferTaskMapper.update(transferTaskDB.getAccountId(), transDto.getTransId(), TaskStatusEnum.SUCCESS.getCode(), TaskStatusEnum.FINISHED.getCode());

            // TODO 手动提交rabbit mq的ack确认
        } catch (Exception e) {
            log.error("message consumer failed ,transId is {}", transDto.getTransId(), e);
        }

    }
}
